"use strict";

var treeArray = [];
var map;
var panelOpen = false;
var tLayers;
var currentTreeNum;
var allTreeNum;

$(document).ready(function () {
    setBodyHeight();
    // 浏览器窗口大小改变时
    $(window).resize(function () {
        setBodyHeight();
    });

    // 右边滑动监听
    rightPanel();

    // 显示地图
    settingMap();

    // 请求数据
    requestData(0);

});

/**
 * 设置body的高度
 */
function setBodyHeight() {
    let page_header = document.getElementById("page_header_container");
    let divHeight = ($(window).height()) -
        (page_header.clientHeight || page_header.offsetHeight);
    $("#page_content_container").height(divHeight);
    $("#page_slide_container").height(divHeight);
}


/**
 * 右边栏点击设置
 */
function rightPanel() {
    $("#right_togger").on("click",function () {
        if(panelOpen){
            $("#right_panel").animate({right: '-250px'});
            $("#right_togger").animate({right: '0'});
            panelOpen = false;
        }else{
            $("#right_panel").animate({right: '0'});
            $("#right_togger").animate({right: '250px'});
            panelOpen = true;
        }
    });
}

/**
 * 地图显示设置
 */
function settingMap() {

    let tiled = new ol.layer.Tile({
        visible: true,
        source: new ol.source.TileWMS({
            url: 'http://218.194.106.110:80/geoserver/test/wms',
            params: {
                'VERSION': '1.1.1',
                tiled: true,
                LAYERS: 'test:新平彝族傣族自治县_卫图_Level_15',
                exceptions: 'application/vnd.ogc.se_inimage',
                tilesOrigin: 101.27532005310059 + "," + 23.63532543182373
            }
        })
    });

    map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),tiled],
        target: document.getElementById("page_content_container"),
        view: new ol.View({
            center: new ol.proj.fromLonLat([101.27532005310059,23.63532543182373]),
            zoom: 10
        })
    });

    // 鼠标移动事件
    map.on('pointermove', function(evt) {
        if (evt.dragging) {
            return;
        }
        // 获取鼠标坐标
        let pixel = map.getEventPixel(evt.originalEvent);
        // 判断获取到的像素是否在Feature区域
        let hit = map.hasFeatureAtPixel(pixel);
        if (hit) {
            // 设置鼠标样式
            map.getTarget().style.cursor = 'pointer';
        } else {
            map.getTarget().style.cursor = '';
        }
    });
}


/**
 * 请求数据
 */
function requestData(id) {
    $.ajax({
        url:"data",
        timeout:60000,
        type:"post",
        data:{"ID":id},
        dataType:"JSON",
        error:function (error) {
            responseError(error);
        },
        success:function (successData) {
            responseSuccess(successData);
        }
    });
}

/**
 * 数据请求成功回调
 */
function responseSuccess(successData) {
    //console.log(successData);
    if(typeof successData === "string"){
        successData = JSON.parse(successData);
    }
    let responseStatus = successData.status;

    if(responseStatus === "ok"){
        // 设置跳转
        currentTreeNum = successData.treeNum.currentNum;
        currentTreeNum = parseInt(currentTreeNum);
        allTreeNum = successData.treeNum.treeNumber;
        allTreeNum = parseInt(allTreeNum);
        $("#mCurrentTree").val(parseInt(currentTreeNum/5));
        $("#mAllTree").text("/"+parseInt(allTreeNum/5));

        formatData(successData.info);
    }else{
        responseError("服务器异常");
    }
}


/**
 * 数据格式化
 */
function formatData(treeInfo) {

    let mIndex = 1;

    treeArray = treeInfo;
    //console.info("server:"+ JSON.stringify(treeArray));

    $(".my_custom_class").empty();

    // 遍历JSON数组
    $.each(treeInfo,function (treeN,treeInfoValue) {
        $.each(treeInfoValue,function (treeM,treeValue) {
            //console.log("value:"+ JSON.stringify(treeValue));
            let pic1Path = treeValue[0].treeImage;
            let pic2Path = treeValue[1].treeImage;
            addInfoNode(mIndex,treeM,pic1Path,pic2Path,treeValue);

            mIndex ++;
        });
    });

    // 点击事件监听
    document.getElementById("info_node").addEventListener("click",
        function (event) {
            let mEvent= event || window.event;
            let target = mEvent.target || mEvent.srcElement;

            let targetID=target.id;
            // 判断id是否存在
            if(targetID){
                //console.log(treeArray[targetID-1]);
                map.removeLayer(tLayers);
                mapPoint(targetID - 1);
            }
    });

    // 画出第一条数据的点
    mapPoint(0);
}


/**
 * 添加信息节点
 */
function addInfoNode(arrayIndex,treeName) {
    let nodeHtml = '<li class="my_custom_class"><a id="'+arrayIndex+'" href=\"#\"><i>'+ arrayIndex
        +'</i><span id="'+arrayIndex+'" class=\"title\">'+treeName+'</span></a>';

    $("#info_node").append(nodeHtml);
}


/**
 * 数据请求失败回调
 */
function responseError(error) {
    alert("请求数据失败："+error);
}


/**
 * 画点
 * @param index
 */
function mapPoint(index) {

    let currentTree = treeArray[index];
    let features = [];

    if(currentTree){
        for(let key in currentTree){
            let mCurrentTree = currentTree[key];
            for(let index in mCurrentTree){
                let mPoint = new ol.proj.fromLonLat([mCurrentTree[index].longitude,mCurrentTree[index].latitude]);
                features[index] = new ol.Feature({
                    'geometry': new ol.geom.Point(mPoint),
                    'i': index
                });
            }
        }
    }

    // 点的样式
    let styles = new ol.style.Style({
        image: new ol.style.Circle({
            radius: 5,
            fill: new ol.style.Fill({color: '#FF0000'}),
            stroke: new ol.style.Stroke({color: '#FF4500', width: 1})
        })
    });

    let vectorSource = new ol.source.Vector({
        features: features,
        wrapX: false
    });
    let vector = new ol.layer.Vector({
        source: vectorSource,
        style: styles
    });
    tLayers = vector;

    map.addLayer(vector);


    // 弹窗设置
    let popup = new ol.Overlay({
        element: document.getElementById('popup')
    });
    let popElement = popup.getElement();
    map.addOverlay(popup);


    let selectSingleClick = new ol.interaction.Select();
    map.addInteraction(selectSingleClick);
    selectSingleClick.on('select', function(evt) {
        let mFeatures = evt.target.getFeatures().getArray();
        if(mFeatures.length > 0) {
            // 清除之前的弹窗
            $(popElement).popover('destroy');
            let pointIndex = mFeatures[0].values_.i;

            let pointTree;
            $.each(currentTree,function (xKey,xValue) {
                pointTree = xValue[pointIndex];
            });

            let pointPosition = pointTree.county + pointTree.town + pointTree.village + pointTree.smallPlaceName;

            // 获取点击位置
            let mCoordinate = evt.mapBrowserEvent.coordinate;
            popup.setPosition(mCoordinate);
            $(popElement).popover({
                placement: 'top',
                animation: false,
                html: true,
                content: '<p>位置：' + pointPosition +'</p><p>估计树龄：'+pointTree.estimatedAge+'</p>' +
                    '<p>树高：'+pointTree.treeHeight+'</p><p>冠幅：'+pointTree.crownAvg+'</p>' +
                    '<p>立地条件：'+pointTree.altitude+'</p>'
            });
            $(popElement).popover('show');

            // 添加图片
            let panelImage = '<img src="getImage?imageAddress='+pointTree.treeImage+'&type=1" class="panel_img" alt="" />';
            $("#right_panel_img").empty().append(panelImage);

            // 画图表
            sensorRequest();
        }
    });

    // 清除弹窗
    map.on('click', function() {
        $(popElement).popover('destroy');
    });
}

/**
 * 页面跳转
 */
function jumpToPage() {
    let xCurrentTree = $("#mCurrentTree").val();

    xCurrentTree = parseInt(xCurrentTree);
    if(xCurrentTree > allTreeNum){
        alert("输入的数据不合法");
    }else{
        requestData(xCurrentTree);
    }
}